package com.example.myapplication.frags;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;

import com.example.myapplication.R;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.data.MessageEvent;
import com.example.myapplication.module_common_service.BooksFragment;
import com.example.myapplication.module_common_service.CourseScoreFragment;
import com.example.myapplication.module_common_service.CoursesFragment;
import com.example.myapplication.module_common_service.FeedBackFragment;
import com.example.myapplication.module_user.LoginActivity;
import com.google.android.material.tabs.TabLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 综述： 需要根据事件总线上是否有 LOGIN_EVENT 和 LOGOUT_EVENT来决定显示什么页面
 */
public class CommonService_Fragment extends Fragment {

    public final static String LOGIN_EVENT = "1";
    public final static String LOGOUT_EVENT = "2";
    AbsoluteLayout root;
    ViewPager vp;
    List<Fragment> subFrags = new ArrayList<>();
    TabLayout tabLayout;
    List<String> tabs = new ArrayList<>();
    int currentSelect;
    TabViewPagerAdapter tabViewPagerAdapter;
    boolean first = true;

    public CommonService_Fragment() {
        // Required empty public constructor
    }

    public static CommonService_Fragment newInstance(String param1, String param2) {
        CommonService_Fragment fragment = new CommonService_Fragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!GlobalData.isLogin) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (!GlobalData.isLogin) {
            root = (AbsoluteLayout) inflater.inflate(R.layout.fragment_user_basic, container, false);
            initLogoutView();
            return root;
        }

        // Inflate the layout for this fragment
        root = (AbsoluteLayout) inflater.inflate(R.layout.fragment_common_service, container, false);
        initLoginedView();
        return root;

    }

    // 登录完成后的页面需要初始化。
    private void initLoginedView() {
        this.vp = root.findViewById(R.id.vp_common);
        this.tabLayout = root.findViewById(R.id.tab_common);
        this.tabs.clear();
        this.subFrags.clear();
        this.tabs.addAll(Arrays.asList("我的借阅", "课程表","成绩查询","报修单填写"));
        this.subFrags.addAll(Arrays.asList(
                new BooksFragment(),
                new CoursesFragment(),
                new CourseScoreFragment(),
                new FeedBackFragment()
        ));
        tabViewPagerAdapter = new CommonService_Fragment.TabViewPagerAdapter(getActivity().getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, subFrags, tabs);

        vp.setAdapter(tabViewPagerAdapter);
        vp.setOffscreenPageLimit(subFrags.size());
        vp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.e(TAG, "onPageScrolled: " + position);
            }

            @Override
            public void onPageSelected(int position) {
                currentSelect = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        tabLayout.setupWithViewPager(vp);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vp.setCurrentItem(tab.getPosition(), false);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        if (vp.getAdapter() instanceof CommonService_Fragment.TabViewPagerAdapter) {
            //源数据有变更后，要及时更新
            ((CommonService_Fragment.TabViewPagerAdapter) vp.getAdapter()).updateFragmentList(subFrags);
        }
        //再选中tab变更之前的tab
        vp.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.selectTab(tabLayout.getTabAt(currentSelect));
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d("common", "onMessageEvent: " + event.getMessage());
        if (event.getMessage().equals(LOGIN_EVENT)) {
            root.removeAllViews();
            // Inflate the layout for this fragment
            getLayoutInflater().inflate(R.layout.fragment_common_service, (ViewGroup) root);
            initLoginedView();
        } else if (event.getMessage().equals(LOGOUT_EVENT)) {
            getLayoutInflater().inflate(R.layout.fragment_user_basic, (ViewGroup) root);
            initLogoutView();
        }

    }

    private void initLogoutView() {
        root.findViewById(R.id.btn_go_login).setOnClickListener(
                view -> {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
        );
    }


    private class TabViewPagerAdapter extends FragmentPagerAdapter {
        private FragmentManager mFragmentManager;
        private List<Fragment> mFragmentList = new ArrayList<>();
        private List<String> tabItems = new ArrayList<>();

        public TabViewPagerAdapter(@NonNull FragmentManager fm, int behavior, List<Fragment> fragmentList, List<String> tabItems) {
            super(fm, behavior);
            mFragmentManager = fm;
            this.tabItems = tabItems;
            updateFragmentList(fragmentList);
        }

        //将每一个item的id指定为fragment的hasCode，确保不会变更
        @Override
        public long getItemId(int position) {
            return mFragmentList.get(position).hashCode();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return this.tabItems.get(position).toString();
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            Fragment instantiateItemFragment = (Fragment) super.instantiateItem(container, position);
            Fragment itemFragment = mFragmentList.get(position);
            //如果集合中对应下标的fragment和fragmentManager中的对应下标的fragment对象一致，则直接返回该fragment
            if (instantiateItemFragment == itemFragment) {
                return instantiateItemFragment;
            } else {
                //如果集合中对应下标的fragment和fragmentManager中的对应下标的fragment对象不一致，那么就是新添加的，所以自己add进入；
                mFragmentManager.beginTransaction().add(container.getId(), itemFragment).commit();
                return itemFragment;
            }
        }


        @Override
        public int getItemPosition(@NonNull Object object) {
            //如果fragment还没有添加过，或者没有包含在里面，则返回没有找到
            if (!((Fragment) object).isAdded() || !mFragmentList.contains(object)) {
                return POSITION_NONE;
            }
            //否则就返回列表中的位置
            return mFragmentList.indexOf(object);
        }


        public void updateFragmentList(List<Fragment> fragmentList) {
            if (!mFragmentList.isEmpty()) {
                mFragmentList.clear();
            }
            mFragmentList.addAll(fragmentList);
            notifyDataSetChanged();
            vp.setOffscreenPageLimit(mFragmentList.size());
        }


        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }
}